package com.ruoyi.common.utils;

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import org.noear.snack.ONode;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AliP2PUtil {


    /**
     * 创建异步任务
     *
     * @return taskId
     */
    public String createAsyncTask(String prompt,String path) {
//        String prompt = "((masterpiece)), ((best quality)), 8k, high detailed, ((2D cartoon style)),(汽车) simplified light and color shading, expressive and varied facial expression, clear outlines, limited to two or three tones, ((pure white background))";
//
        ImageSynthesisResult result = null;
        try {
         //   String encodedObjectName = URLDecoder.decode("Object_3k/2_Man-made/2_Vehicles/1%E6%B1%BD%E8%BD%A6/swtp_01752_la.jpg", "UTF-8");
            path = path.replaceAll("\\\\", "/");
            String sketchImageUrl = "https://codingok.oss-cn-beijing.aliyuncs.com/" + path;

//        String sketchImageUrl = "https://help-static-aliyun-doc.aliyuncs.com/assets/img/zh-CN/6609471071/p743851.jpg";
            String model = "wanx-sketch-to-image-lite";
            ImageSynthesisParam param = ImageSynthesisParam.builder()
                    .model(model)
                    .prompt(prompt)
                    .n(4)
                    .size("768*768")
                    .sketchImageUrl(sketchImageUrl)
                    .style("<flat illustration>")
                    .build();
            String task = "image2image";
            ImageSynthesis imageSynthesis = new ImageSynthesis(task);
            result = imageSynthesis.asyncCall(param);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        String taskId = result.getOutput().getTaskId();
        System.out.println("taskId=" + taskId);
        return taskId;
    }


    /**
     * 等待异步任务结束
     *
     * @param taskId 任务id
     */
    public  static Map<String, List<String>> waitAsyncTask(String taskId) {
        Map<String, List<String>> resultMap = new HashMap<>();
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            // If you have set the DASHSCOPE_API_KEY in the system environment variable, the apiKey can be null.
            result = imageSynthesis.wait(taskId, null);
            System.out.println(JsonUtils.toJson(result));
        } catch (ApiException | NoApiKeyException e) {
            throw new RuntimeException(e.getMessage());
        }
        ONode oNode = ONode.load(result.getOutput().getResults());
        List<String> urlList = oNode.select("$.url").toObjectList(String.class);
        resultMap.put(taskId,urlList);

        System.out.println(JsonUtils.toJson(resultMap));
        return resultMap;
    }


    public void syncCankaoCall() {
        String prompt = "((masterpiece)), ((best quality)), 8k, high detailed, ((2D cartoon style)),(闪电) simplified light and color shading, expressive and varied facial expression, clear outlines, limited to two or three tones, ((pure white background))";
        //使用公网url链接
        String refImage = "https://codingok.oss-cn-beijing.aliyuncs.com/lineart/swtp_00853_la.jpg";
        HashMap<String, Object> parameters = new HashMap<>();
        parameters.put("ref_strength", 0.35);
        parameters.put("ref_mode", "repaint");

        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(ImageSynthesis.Models.WANX_V1)
                        .prompt(prompt)
                        .style("<auto>")
                        .n(1)
                        .size("1024*1024")
                        .refImage(refImage)
                        .parameters(parameters)
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            System.out.println("---sync call, please wait a moment----");
            result = imageSynthesis.call(param);
        } catch (ApiException | NoApiKeyException e) {
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
    }


    public static void main(String[] args) {
        AliP2PUtil text2Image = new AliP2PUtil();
        String prompt ="((masterpiece)), ((best quality)), 8k,  pop art style depiction of a vintage ,the reference image generate  pop-art style image outline of the lightning. simplified design with clean lines and flat shapes,The images are generally simplified, consisting of clean lines and shapes rather, dynamic composition, no intricate details. ";
        String path="E:\\动漫采集\\线稿\\Object_3k\\1_Natural\\3_Natural\\4_lightning\\swtp_00854_la.jpg";
        String taskId= text2Image.createAsyncTask( prompt, path);
//        text2Image.waitAsyncTask(taskId);
    }
}
